# !/usr/bin/env python
# -*- coding: utf-8 -*-

# @ author = 'zoushunli'
# @ author_email = '409358374@qq.com'
import json
# import MongoDB
import os

import subprocess

import requests

from lxml import etree

# 防止因https证书问题报错

requests.packages.urllib3.disable_warnings()
headers = {
    
    # 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0',
    # 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 Edge/15.15063',
    'Referer': 'https://www.bilibili.com/',
    'Connection': 'keep-alive',
    'Accept': 'application/json, text/plain, */*',
    'Sec-Fetch-Dest': 'empty',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Origin': 'https://live.bilibili.com',
    'Sec-Fetch-Site': 'same-site',
    'Sec-Fetch-Mode': 'cors',
    'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-TW;q=0.6',
    
}

'''

    获取bilibili视频的主要函数

    @param url 视频页面url 结构为:url?参数

    @param p 视频p数

    @param bv 视频bv数

'''


def getBiliBiliVideo(url, p, bv):
    session = requests.session()
    
    res = session.get(url=url, headers=headers, verify=False)
    
    _element = etree.HTML(res.content)
    
    # 获取window.__playinfo__的json对象,[20:]表示截取'window.__playinfo__='后面的json字符串
    
    videoPlayInfo = str(_element.xpath('//head/script[3]/text()')[0].encode('utf-8').decode('utf-8'))[20:]
    
    videoJson = json.loads(videoPlayInfo)
    
    # 获取视频链接和音频链接
    
    try:
        
        # 2018年以后的b站视频由.audio和.video组成
        
        videoURL = videoJson['data']['dash']['video'][0]['baseUrl']
        
        audioURl = videoJson['data']['dash']['audio'][0]['baseUrl']
        
        flag = 0
    
    except Exception:
        
        # 2018年以前的b站视频音频视频结合在一起,后缀为.flv
        
        videoURL = videoJson['data']['durl'][0]['url']
        
        flag = 1
    
    # 指定文件生成目录,如果不存在则创建目录
    
    dirname = ("E:/result").encode("utf-8").decode("utf-8")
    
    if not os.path.exists(dirname):
        os.makedirs(dirname)
        
        print('文件夹创建成功!')
    
    # 获取每一集的名称
    
    name = bv + "-" + str(p)
    
    # 下载视频和音频
    
    print('正在下载 "' + name + '" 的视频····')
    
    fileDownload(homeurl=url, url=videoURL, name='E:/result/' + name + '_Video.mp4', session=session)
    
    if flag == 0:
        print('正在下载 "' + name + '" 的音频····')
        
        fileDownload(homeurl=url, url=audioURl, name='E:/result/' + name + '_Audio.mp3', session=session)
        
        print('正在组合 "' + name + '" 的视频和音频····')
        
        combineVideoAudio('E:/result/' + name + '_Video.mp4', 'E:/result/' + name + '_Audio.mp3',
                          'E:/result/' + name + '_output.mp4')
    
    print(' "' + name + '" 下载完成！')


'''
    使用session保持会话下载文件
    
    @param homeurl 访问来源
    
    @param url 音频或视频资源的链接
    
    @param name 下载后生成的文件名
    
    @session 用于保持会话
'''


def fileDownload(homeurl, url, name, session=requests.session()):
    # 添加请求头键值对,写上 refered:请求来源
    
    headers.update({'Referer': homeurl})
    
    # 发送option请求服务器分配资源
    
    session.options(url=url, headers=headers, verify=False)
    
    # 指定每次下载1M的数据
    
    begin = 0
    
    end = 1024 * 512 - 1
    
    flag = 0
    
    while True:
        
        # 添加请求头键值对,写上 range:请求字节范围
        
        headers.update({'Range': 'bytes=' + str(begin) + '-' + str(end)})
        
        # 获取视频分片
        
        res = session.get(url=url, headers=headers, verify=False)
        
        if res.status_code != 416:
            
            # 响应码不为为416时有数据
            
            begin = end + 1
            
            end = end + 1024 * 512
        
        else:
            
            headers.update({'Range': str(end + 1) + '-'})
            
            res = session.get(url=url, headers=headers, verify=False)
            
            flag = 1
        
        with open(name.encode("utf-8").decode("utf-8"), 'ab') as fp:
            
            fp.write(res.content)
            
            fp.flush()
        
        # data=data+res.content
        
        if flag == 1:
            fp.close()
            
            break


'''

    用于合并音频与视频

    @param videopath 视频路径

    @param audiopath 音频路径

    @param outpath 生成合并视频的路径

'''


def combineVideoAudio(videopath, audiopath, outpath):
    subprocess.call((
                            "D:/python/ffmpeg-3.4.2-win64-static/bin/ffmpeg -i " + videopath + " -i " + audiopath + " -c copy " + outpath).encode(
        "utf-8").decode("utf-8"), shell=True)
    
    os.remove(videopath)
    
    os.remove(audiopath)


import requests
import json
import time
# import paho.mqtt.client as mqtt

HOST = "solasolo.oicp.net"
PORT = 1883

def getdm(roomid):
    global count
    cookies = {
        '$CURRENT_FNVAL': '16',
        '_uuid': '8F5A3A04-3516-688F-DFD9-1753EA4066F447985infoc',
        'LIVE_BUVID': 'AUTO6515732103534301',
        'stardustvideo': '1',
        'laboratory': '1-1',
        'rpdid': '|(J|JuukRu|Y0J\'ul~Jku|R|k',
        'buvid3': 'A194E945-535A-42A3-8750-6FE3F276CE8D155809infoc',
        'im_notify_type_393348954': '0',
        'CURRENT_QUALITY': '80',
        'DedeUserID': '393348954',
        'DedeUserID__ckMd5': '93fe03331b2665fe',
        'SESSDATA': '65dd27bc%2C1599566176%2C3f1cc*31',
        'bili_jct': 'abf20064ef38b1446eca56cca1b00fe5',
        'Hm_lvt_8a6d461cf92ec46bd14513876885e489': '1581755955,1584171299,1584171568,1584171588',
        'Hm_lpvt_8a6d461cf92ec46bd14513876885e489': '1584171588',
        '_dfcaptcha': '369355ebdd21c3cc50827acbfa7b5e75',
        'PVID': '21',
        'Hm_lvt_8a6e55dbd2870f0f5bc9194cddf32a02': '1584011095,1584098246,1584098316,1584171697',
        'Hm_lpvt_8a6e55dbd2870f0f5bc9194cddf32a02': '1584171697',
    }
    
    headers = {
        'Connection': 'keep-alive',
        'Accept': 'application/json, text/plain, */*',
        'Sec-Fetch-Dest': 'empty',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Origin': 'https://live.bilibili.com',
        'Sec-Fetch-Site': 'same-site',
        'Sec-Fetch-Mode': 'cors',
        'Referer': 'https://live.bilibili.com/' + roomid,
        'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-TW;q=0.6',
    }
    
    data = {
        'roomid': roomid,
        'csrf_token': 'abf20064ef38b1446eca56cca1b00fe5',
        'csrf': 'abf20064ef38b1446eca56cca1b00fe5',
        'visit_id': ''
    }
    response = requests.post('https://api.live.bilibili.com/ajax/msg', headers=headers, cookies=cookies, data=data)
    # print(response.text)
    result = response.json()
    danmus = result['data']['room']
    list1 = []
    f = open("piday.txt", "r", encoding="utf-8")
    for line in f.readlines():
        list1.append(line.replace("\n", ""))
    # print(list1)
    
    for danmu in danmus:
        print("%s 网友:%s  评论了:%s" % (danmu['timeline'], danmu['nickname'], danmu['text']))
        if ("%s 网友:%s  评论了:%s" % (danmu['timeline'], danmu['nickname'], danmu['text'])) in list1:
            print("已经有了")
        else:
            print("新弹幕:")
            
            print("%s 网友:%s  评论了:%s" % (danmu['timeline'], danmu['nickname'], danmu['text']),
                  file=open("piday.txt", "a", encoding="utf-8"))
            if danmu['text'] == "#加油":
                count += 1
                test(count, "1")
            if danmu['text'] == "#加量":
                count += 1
                test(count, "10")



def test_(url):
    session = requests.session()
    res = session.get(url=url, headers=headers, verify=False)
    print(res.text)
    # _element = etree.HTML(res.content)
# test_('https://www.bilibili.com/video/BV1bs411h7gN?p=35')
test_('https://space.bilibili.com/15960317/video')
# if __name__ == '__main__':
#
#     # 输入bilibili视频的BV号
#
#     bv = input('视频BV号：')
#
#     url = 'https://www.bilibili.com/video/' + bv
#
#     # 选择视频从第几p开始到第几p结束
#
#     startPart = input('起始P:')
#
#     endPart = input('终止P;')
#
#     for p in range(int(startPart), int(endPart) + 1):
#         getBiliBiliVideo(url + '?p=' + str(p), p, bv)
